package main

import (
	_ "embed"
	"encoding/json"
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/widget"
	"log"
	"net"
	core2 "screenRobot/client/core"
	"screenRobot/network"
	"screenRobot/network/udp"
	"screenRobot/server/core"
)

//go:embed logo.png
var logoIco []byte

func main() {
	application := app.New()
	application.Settings().SetTheme(&myTheme{})
	logoResource := fyne.NewStaticResource("logo", logoIco)
	application.SetIcon(logoResource)

	//启动监听寻找服务端
	var addrChan = make(chan *net.UDPAddr)
	go udp.Client(addrChan)

	//创建窗口
	master := application.NewWindow("四点五robot 用户端")
	master.Resize(fyne.NewSize(300, 0))
	hint := binding.NewString()
	hint.Set("正在搜索服务器...")
	progressBar := widget.NewProgressBarInfinite()

	//开启协程寻找服务器
	go func() {
		for {
			addr := <-addrChan
			//显示连接到服务器
			hint.Set(fmt.Sprintf("服务器地址：%s:%d", addr.IP, addr.Port))
			progressBar.Hide()

			//创建tcp连接
			conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: addr.IP, Port: addr.Port})
			if network.Handler("连接服务器tcp失败", err) {
				log.Println("连接tcp服务失败！")
				hint.Set("连接tcp服务器失败，请检查服务端是否开启...")
				break
			}
			go HandleServerMessage(conn)

			//发送通知
			application.SendNotification(fyne.NewNotification("连接客户端成功", fmt.Sprintf("服务端信息：IP：%s 端口：%d\n后台运行中...", addr.IP, addr.Port)))

			break
		}
	}()
	master.Resize(fyne.NewSize(200, 50))
	master.SetContent(
		container.NewCenter(container.NewVBox(widget.NewLabelWithData(hint), progressBar)))
	master.ShowAndRun()
}

// HandleServerMessage 处理服务器信息
func HandleServerMessage(conn *net.TCPConn) {
	defer conn.Close()
	buffer := make([]byte, 1024)
	for {
		size, err := conn.Read(buffer)
		if network.Handler("读取信息失败：", err) {
			continue
		}
		var keyMouse core.KeyMouse
		json.Unmarshal(buffer[:size], &keyMouse)
		log.Println("收到服务器信息：", keyMouse)
		//鼠标移动
		core2.MouseHandle(keyMouse)

		//按键松开或者按下
		core2.KeyDown(keyMouse.DownKey)
		core2.KeyUp(keyMouse.UpKey)
	}
}
